﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Sql;
using System.Data;
using Maticsoft.DBUtility;
using System.Collections;
using System.Windows.Forms;

namespace Maticsoft.Common
{
    public class Servers
    {
        //存储数据库
        public static string GlobalSql {get;set;}

        public static Hashtable old_db = new Hashtable();
        public static Hashtable new_db = new Hashtable();
        /// <summary>
        /// 获取服务器
        /// </summary>
        /// <returns></returns>
        public static DataTable GetServers()
        {
            try
            {
                SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
                DataTable dt = instance.GetDataSources();
                while(dt.Rows.Count <=0 )
                {
                    if(MessageBox.Show("网路繁忙是否重试","提示",MessageBoxButtons.YesNo).Equals(DialogResult.No)) break;
                    dt = instance.GetDataSources();
                }
                return dt;
            }
            catch { return null; }
        }

        /// <summary>
        /// 获取数据表
        /// </summary>
        /// <returns></returns>
        public static DataTable GetDatabasess(String server,String uid, String pwd, Boolean bol)
        {
            try
            {
                string sql1 = "server={0};database={1};uid={2};pwd={3};";
                string sql2 = "Data Source={0};Initial Catalog={1};Integrated security=SSPI;";
                if (bol)
                {
                    DbHelperSQL.connectionString = string.Format(sql1, server, "master", uid, pwd);
                    GlobalSql = string.Format(sql1, server, "{0}", uid, pwd);
                }
                else
                {
                    DbHelperSQL.connectionString = string.Format(sql2, server, "master", uid, pwd);
                    GlobalSql = string.Format(sql2, server, "{0}", uid, pwd);
                }
                return DbHelperSQL.Query("select [name] from master.dbo.sysdatabases order by [name]").Tables[0];
            }
            catch { return null; }
        }

        /// <summary>
        /// 查询数据表
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static DataTable GetTables(string data)
        {
            try
            {
                string sql1 = "select [name] from sysobjects where xtype='u' order by [name]";
                DbHelperSQL.connectionString = string.Format(GlobalSql, data);
                return DbHelperSQL.Query(sql1).Tables[0];
            }
            catch { return null; }
        }
    }
}
 